package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class DeviceTravelActivity extends AppActivity {
    private int step = 1;
    private String queryCode;
    private int totalTime = 20 * 1000;
    private long startTime;
    private String serialNo;
    private ImageView upImageView;
    private TextView upTextView;
    private ImageView pauseImageView;
    private TextView pauseTextView;
    private ImageView downImageView;
    private TextView downTextView;
    private ImageView setImageView;
    private TextView setTextView;
    private TextView tipsTextView;
    private DeviceBean deviceBean;
    public static void start(Context context, String serialNo) {
        Intent intent = new Intent(context, DeviceTravelActivity.class);
        intent.putExtra("serialNo", serialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_travel;
    }

    @Override
    protected void initView() {
        serialNo = getString("serialNo");
        upImageView = findViewById(R.id.iv_curtain_up);
        upTextView = findViewById(R.id.tv_curtain_up);
        pauseImageView = findViewById(R.id.iv_curtain_pause);
        pauseTextView = findViewById(R.id.tv_curtain_pause);
        downImageView = findViewById(R.id.iv_curtain_down);
        downTextView = findViewById(R.id.tv_curtain_down);
        setImageView = findViewById(R.id.iv_curtain_maximum);
        setTextView = findViewById(R.id.tv_curtain_maximum);
        tipsTextView = findViewById(R.id.tv_content);
        setOnClickListener(R.id.iv_curtain_up,R.id.iv_curtain_pause,R.id.iv_curtain_down,R.id.iv_curtain_reverse,R.id.iv_curtain_maximum,R.id.iv_curtain_reset);
    }

    @Override
    protected void initData() {
        deviceBean = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(serialNo);
        if(deviceBean.getDeviceType().equals("bofu_windowcurtains") || deviceBean.getDeviceType().equals("bofu_windowcurtains")){
            upImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_curtain_angle_left));
            downImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_curtain_angle_right));
            upTextView.setText("向左");
            downTextView.setText("向右");
            setImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_curtain_angle_180));
            setTextView.setText("设为最左点");
            tipsTextView.setText("请选定最左点，设置角度。 \\n如果按键方向相反，请点击“电机反向”按钮。");
        }
    }

    private void rebuildView(){
        if(deviceBean.getDeviceType().equals("dream_windowcurtains") || deviceBean.getDeviceType().equals("bofu_windowcurtains")){
            if(step == 2){
                setImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_curtain_angle_0));
                setTextView.setText("设为最右点");
                tipsTextView.setText("请选定最右点，设置角度。 \\n如果按键方向相反，请点击“电机反向”按钮。");
            }else{
                setImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_curtain_angle_180));
                setTextView.setText("设为最左点");
                tipsTextView.setText("请选定最左点，设置角度。 \\n如果按键方向相反，请点击“电机反向”按钮。");
            }
        }else{
            if(step == 2){
                setImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_travel_curtain_lowest));
                setTextView.setText(R.string.travel_setting_lowest);
                tipsTextView.setText(R.string.blinds_step_2_message);
            }else{
                setImageView.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_travel_curtain_highest));
                setTextView.setText(R.string.travel_setting_highest);
                tipsTextView.setText(R.string.blinds_step_1_message);
            }
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_curtain_up:
                operationDevice(2);
                break;
            case R.id.iv_curtain_pause:
                operationDevice(3);
                break;
            case R.id.iv_curtain_down:
                operationDevice(1);
                break;
            case R.id.iv_curtain_reverse:
//                step = 0;
                motorReverse();
                break;
            case R.id.iv_curtain_maximum:
                if(step == 1 || step == 0){
                    setTravel(1);
                }else{
                    setTravel(2);
                }
                break;
            case R.id.iv_curtain_reset:
                step = 3;
                setTravel(3);
                break;
        }
    }

    private void operationDevice(int strokeState){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.STROKE_STATE, strokeState);
        Map<String, Object> status = new HashMap<>();
        status.put("status", option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), serialNo, status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
//                ToastUtils.show("执行成功");
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private Runnable countRunnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentTimeMillis() - startTime > totalTime){
                handleFailed();
            }else{
                postDelayed(this, 990);
            }
        }
    };

    private void setTravel(int value){
        startTime = System.currentTimeMillis();
        post(countRunnable);
        Map<String, Object> stateData = new HashMap<>();
        Map<String, Object> settings = new HashMap<>();
        settings.put("travelsetting", value);
        stateData.put("settings", settings);
        LLHttpManager.sendDeviceSetting(this, serialNo, stateData, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity)getContext()).showDialog(getResources().getString(R.string.setting));
                }
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

    private void motorReverse(){
        startTime = System.currentTimeMillis();
        post(countRunnable);
        Map<String, Object> stateData = new HashMap<>();
        Map<String, Object> settings = new HashMap<>();
        settings.put("td_setting", 1);
        stateData.put("settings", settings);
        LLHttpManager.sendDeviceSetting(this, serialNo, stateData, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity)getContext()).showDialog(getResources().getString(R.string.setting));
                }
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

    private void querySendDeviceSetting(){
        LLHttpManager.querySendDeviceSetting(this, queryCode, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null){
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void handleResult(QueryCodeResultBean data){
        queryCode = data.getQueryCode();
        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
        if(data != null){
            switch (data.getQueryStateType()){
                case 0:
                case 1:
                    getHandler().postDelayed(pollingRunnable, 1000);
                    break;
                case 2:
                    getHandler().removeCallbacksAndMessages(null);
                    ToastUtils.show(R.string.set_success);
                    hideDialog();
                    if(step == 1){
                        step = 2;
                        rebuildView();
                    }else if(step == 3){
                        step = 1;
                        rebuildView();
                    }else{
                        finish();
                    }
                    break;
                case 3:
                case 4:
                case 5:
                    handleFailed();
                    break;
            }
        }
    }

    private void handleFailed(){
        getHandler().removeCallbacksAndMessages(null);
        ToastUtils.show(R.string.set_failed);
        hideDialog();
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            querySendDeviceSetting();
        }
    };
}
